import { useRef, useState, memo } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { NavBar, Form, Input, Button } from 'antd-mobile';
import { getPhoneCode, login } from '@/api';
import showToast from '@/utils/toast';
import LoginWrapper from './style';
import cache from '@/utils/cache';
import { connect } from 'react-redux';
import actions from '@/store/actions';

const Login = memo((props) => {
  const navigate = useNavigate(),
    searchParams = useSearchParams(),
    formRef = useRef(null),
    timer = useRef(null);
  let [time, setTime] = useState(60);

  // 表单校验
  const rules = {
    phoneRules: [
      { required: true, type: 'string', len: 11, message: '请输入11位手机号' },
      { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' }
    ],
    codeRules: [{ required: true, type: 'string', len: 6, message: '请输入6位验证码' }]
  };

  // 重置倒计时间
  const resetTime = () => {
    clearInterval(timer.current);
    setTime(60);
    timer.current = null;
  };
  // 发送验证码
  const sendCode = async () => {
    if (timer.current) return;
    // 校验用户输入的手机号
    const validateRes = await formRef.current.validateFields(['phone']);
    try {
      const { code } = await getPhoneCode(validateRes.phone);
      timer.current = setInterval(() => {
        time--;
        setTime(time);
        if (time <= 0) resetTime();
      }, 1000);
      if (code !== 0) {
        showToast('获取验证码失败');
        resetTime();
      }
    } catch (_) {}
  };

  const { getUserInfo } = props;
  const submit = async (values) => {
    try {
      const { code, token } = await login(values);
      if (+code !== 0) return showToast('登录失败');
      resetTime();
      cache.setCache('token', token);
      await getUserInfo();
      const to = searchParams[0].get('to');
      navigate(to ? to : '/home', { replace: true });
    } catch (_) {}
  };

  return (
    <LoginWrapper>
      <NavBar onBack={() => navigate('/home', { replace: true })}>登录/注册</NavBar>
      <Form
        ref={formRef}
        onFinish={(values) => submit(values)}
        layout="horizontal"
        footer={
          <Button className="submit-btn" block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        <Form.Item label="手机号" name="phone" rules={rules.phoneRules}>
          <Input maxLength={11} placeholder="请输入手机号" clearable />
        </Form.Item>
        <Form.Item
          label="短信验证码"
          name="code"
          rules={rules.codeRules}
          extra={
            <div>
              <Button disabled={!!timer.current} onClick={() => sendCode()} color="primary" fill="none">
                {timer.current ? `${time}s` : '获取验证码'}
              </Button>
            </div>
          }
        >
          <Input maxLength={6} placeholder="请输入验证码" clearable />
        </Form.Item>
      </Form>
    </LoginWrapper>
  );
});

export default connect(null, actions.base)(Login);
